<template>
  <div>
    <h1>订单信息</h1>
    <el-form label-width="130px" class="commonFrom">
      <el-form-item label="合同编号：" style="margin-bottom: 3px; margin-right: 500px">
        <el-select
          size="small"
          v-if="!orderId"
          v-model.trim="orderFrom.contractId"
          placeholder="请选择合同编号"
          @change="contractChange"
        >
          <el-option
            v-for="item in conOptions"
            :key="item.id"
            :label="item.contractNo"
            :value="item.id"
            :disabled="!item.choose"
          >
            <span>{{ item.contractNo }}</span>
            <span v-if="!item.choose" style="float: right">--虚拟账户待同步!</span>
          </el-option>
        </el-select>
        <span v-else> {{ orderFrom.contractNo }}</span>
      </el-form-item>
      <el-form-item label="工程名称：" style="margin-bottom: 3px !important">
        {{ orderFrom.proName || '--' }}
      </el-form-item>
      <el-form-item label="供应商：" style="margin-bottom: 3px !important">
        {{ orderFrom.providerName || '--' }}
      </el-form-item>
      <el-form-item label="交付地点：" style="width: 100% !important; margin-bottom: 12px !important">
        <el-select
          style="width: 150px"
          size="small"
          v-model.trim="orderFrom.provinceId"
          placeholder="请选择省"
          @change="provinceChange($event, 'clear')"
        >
          <el-option
            v-for="item in provinceOptions"
            :key="item.provinceId"
            :label="item.province"
            :value="item.provinceId"
          >
          </el-option>
        </el-select>
        <el-select
          style="width: 150px; margin-left: 10px"
          size="small"
          v-model.trim="orderFrom.cityId"
          placeholder="请选择市"
          @change="cityChange($event, 'clear')"
        >
          <el-option v-for="item in cityOptions" :key="item.cityId" :label="item.city" :value="item.cityId">
          </el-option>
        </el-select>
        <el-select
          style="width: 150px; margin-left: 10px"
          size="small"
          v-model.trim="orderFrom.areaId"
          placeholder="请选择区"
          @change="areaChange"
        >
          <el-option v-for="item in areaOptions" :key="item.areaId" :label="item.area" :value="item.areaId">
          </el-option>
        </el-select>
        <el-input
          style="width: 280px; margin-left: 10px"
          size="small"
          placeholder="请填写详细地址"
          v-model.trim="orderFrom.detailAddress"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="约定交货日期：" style="margin-right: 500px; margin-bottom: 3px !important">
        <el-date-picker
          size="small"
          style="width: 280px"
          :picker-options="pickerOptions0"
          v-model.trim="orderFrom.agreedDeliveryDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采购商名称："> {{ orderFrom.enterpriseName || '--' }} </el-form-item>
      <el-form-item label="签约采购商："> {{ orderFrom.contractBuyer || '--' }} </el-form-item>
    </el-form>
    <div style="margin-bottom: 20px">
      以下甲方即指合同中采购方，乙方即指合同中的供应方:乙方根据甲方实际需要，以{{ createTime || 'xx年xx月xx日' }}签订的
      《{{ noAndName || 'xxxx' }}》 为依据，乙方将按下表所列材料(设备)名
      称、品牌、型号.规格、数量.交货日期送至甲方指定的交货地点送货。
    </div>
    <h1>货品清单</h1>
    <div class="btn_box">
      <div>
        <el-button size="small" icon="iconfont icon-add" class="commonBtn1" @click="addMaterial('合同内')"
          >添加合同内材料</el-button
        >
        <el-button size="small" icon="iconfont icon-add" class="commonBtn1" @click="addMaterial('合同外')"
          >添加合同外材料</el-button
        >
        <el-button size="small" class="commonBtn" @click="remove">清空</el-button>
      </div>
      <p>
        总合计：<span style="font-size: 24px; color: #333">{{ orderFrom.amountPrice || '0' }}</span
        >元
      </p>
    </div>
    <div style="margin-bottom: 20px">
      <el-table
        :data="orderFrom.detailsList"
        border
        class="bidding"
        tooltip-effect="light"
        ref="jdjgTable"
        :header-cell-style="{ padding: '0px', background: '#F2F3F7' }"
        :row-class-name="tabRowClassName"
      >
        <el-table-column width="60" align="center" type="index" label="序号">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="材料类型" align="center" prop="productTypes" width="160">
          <template slot-scope="scope">
            <div>
              {{ scope.row.productTypes == 1 ? '合同内' : '合同外' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="材料名称" align="center" prop="materialName" width="160"> </el-table-column>
        <el-table-column label="规格型号" align="center" prop="model" width="160">
          <template slot-scope="scope">
            <el-select
              size="small"
              v-if="scope.row.productTypes == 2"
              v-model.trim="scope.row.model"
              placeholder="请选择"
              @change="categoryChange"
              @visible-change="selectFocus($event, scope.row.materialId)"
            >
              <el-option
                v-for="item in scope.row.modelSelectList"
                :label="item.specsName"
                :value="item.specsName"
                :key="item.id"
              ></el-option>
            </el-select>
            <div v-else>
              {{ scope.row.model }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="company" width="120"> </el-table-column>
        <el-table-column label="参数指标" align="center" prop="parameterIndex" width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-if="scope.row.productTypes == 1" class="text_hidde">
              {{ scope.row.parameterIndex }}
            </div>
            <div v-else>
              <tool-tip-input
                :size="'small'"
                :deviationContent="scope.row.parameterIndex"
                v-model.trim="scope.row.parameterIndex"
                :placeholder="'请输入参数指标'"
              ></tool-tip-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="unitPrice" width="140">
          <template slot-scope="scope">
            <div>
              <el-input
                v-model.trim="scope.row.unitPrice"
                placeholder="请输入单价"
                size="small"
                @input="contractPrice($event, scope.$index, 'unitPrice')"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="purchaseQuantity" width="140">
          <template slot-scope="scope">
            <div>
              <el-input
                v-model.trim="scope.row.purchaseQuantity"
                placeholder="请输入数量"
                size="small"
                @input="contractPrice($event, scope.$index, 'purchaseQuantity')"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center" prop="totalPrice" width="160"> </el-table-column>
        <el-table-column label="操作" align="center" width="140" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="ty czBtn" @click="delTableItem(scope.$index)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <h1>送货约定</h1>
    <el-input
      type="textarea"
      :autosize="{ minRows: 3 }"
      placeholder="请输入送货说明"
      v-model.trim="orderFrom.agreedDelivery"
      style="margin: 20px 0"
    >
    </el-input>
    <h1>审核人员</h1>
    <el-button size="small" type="primary" class="commonBtn1 mgn" icon="iconfont icon-add" @click="addReviewer"
      >添加审核人员</el-button
    >
    <el-form class="commonFrom auditfrom" label-width="110px">
      <el-form-item v-for="(item, index) in reviewerList" :key="index" :label="'审核人员' + (index + 1) + '：'">
        <el-input
          style="width: 220px"
          class="no_border"
          disabled
          size="small"
          placeholder="请选择审核人员"
          v-model.trim="item.approverName"
        >
          <el-button @click="personnelSelect('reviewer', index)" slot="append">选择</el-button>
        </el-input>
        <i class="iconfont icon-guanbianniu" @click="colseReviewer(index)"></i>
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button size="small" class="commonBtn" @click="closeBtn">取消</el-button>
      <el-button size="small" class="commonBtn1" @click="subBtn">确定</el-button>
    </div>

    <el-dialog
      width="765px"
      :center="true"
      title="选择联系人"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="personVisible"
      v-if="personVisible"
    >
      <personnel-select :type="personType" :index="reviewerIndex" @close="personClose"></personnel-select>
    </el-dialog>
    <el-dialog
      width="1200px"
      :center="true"
      title="选择材料"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="addMaterialVisiable"
      v-if="addMaterialVisiable"
    >
      <add-contract-material :contractId="orderFrom.contractId" @close="materialClose"></add-contract-material>
    </el-dialog>
    <el-dialog
      class="dialog_detail"
      :center="true"
      append-to-body
      :close-on-click-modal="false"
      width="1200px"
      title="选择新品类"
      :visible.sync="materialVisible"
      v-if="materialVisible"
    >
      <tertiary-material :list="[]" @close="newMaterialClose"> </tertiary-material>
    </el-dialog>
  </div>
</template>

<script>
import tertiaryMaterial from '../../../../components/TertiaryMaterial'
import ToolTipInput from '../../../../components/ToolTipInput.vue'
import personnelSelect from '../../../../components/PersonnelSelect'
import AddContractMaterial from './AddContractMaterial.vue'
export default {
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      createTime: '',
      noAndName: '',
      conOptions: [],
      cityOptions: [],
      areaOptions: [],
      provinceOptions: [],
      reviewerList: [
        {
          approverName: '',
          approverId: ''
        }
      ],
      materialVisible: false,
      addMaterialVisiable: false,
      personVisible: false,
      personType: '',
      reviewerIndex: '',
      orderFrom: {
        contractId: '',
        contractNo: '',
        proName: '',
        proId: '',
        enterpriseId: localStorage.getItem('enterpriseId'),
        enterpriseName: '',
        contractBuyer: '',
        providerId: '',
        providerName: '',
        area: '',
        areaId: '',
        city: '',
        cityId: '',
        provinceId: '',
        province: '',
        detailAddress: '',
        detailsList: [],
        approveDtoList: [],
        agreedDeliveryDate: '',
        agreedDelivery: '',
        amountPrice: ''
      }
    }
  },
  props: {
    orderId: {
      type: [String, Number]
    }
  },
  components: { personnelSelect, AddContractMaterial, ToolTipInput, tertiaryMaterial },
  mounted() {
    if (this.orderId) {
      this.getOrderData()
    } else {
      this.getData()
    }
    this.getSelect()
  },
  methods: {
    remove() {
      this.orderFrom.detailsList.forEach(item => {
        if (item.productTypes == 2) {
          this.$set(item, 'parameterIndex', '')
        }
        this.$set(item, 'unitPrice', '')
        this.$set(item, 'purchaseQuantity', '')
        this.$set(item, 'totalPrice', '')
      })
      this.calculatePrice()
    },
    // 计算价格
    contractPrice(e, index, prop) {
      if (e) {
        if (prop === 'purchaseQuantity') {
          if (!this.common.fieldTest('count', e)) {
            this.orderFrom.detailsList[index][prop] = 0
            this.$message.error('你输入的数量格式有误或超出范围,请重新输入')
            this.$set(this.orderFrom.detailsList[index], 'totalPrice', '')
            this.calculatePrice()
            return false
          }
        } else {
          if (!this.common.fieldTest('money', e)) {
            this.orderFrom.detailsList[index][prop] = 0
            this.$message.error('你输入的单价格式有误或超出范围,请重新输入')
            this.$set(this.orderFrom.detailsList[index], 'totalPrice', '')
            this.calculatePrice()
            return false
          }
        }
      }
      this.$set(this.orderFrom.detailsList[index], prop, e)
      if (this.orderFrom.detailsList[index].unitPrice && this.orderFrom.detailsList[index].purchaseQuantity) {
        let price =
          (this.orderFrom.detailsList[index].unitPrice * 100 * this.orderFrom.detailsList[index].purchaseQuantity) / 100
        this.$set(this.orderFrom.detailsList[index], 'totalPrice', price.toFixed(2))
      } else {
        this.$set(this.orderFrom.detailsList[index], 'totalPrice', '')
      }

      this.calculatePrice()
    },
    subBtn() {
      // 过滤出id存在的审核人
      this.orderFrom.approveDtoList = this.reviewerList.filter(item => {
        return item.approverId
      })
      // 判断标书内清单是否存在未填写数量以及单价的
      let inBidFlag = this.orderFrom.detailsList.some(item => {
        return !item.purchaseQuantity || !item.unitPrice
      })
      if (!this.orderFrom.contractId) {
        this.$message.error('请选择合同编号')
        return false
      } else if (
        !this.orderFrom.areaId ||
        !this.orderFrom.provinceId ||
        !this.orderFrom.cityId ||
        !this.orderFrom.detailAddress
      ) {
        this.$message.error('请精确填写交付地点')
        return false
      } else if (!this.orderFrom.agreedDeliveryDate) {
        this.$message.error('请选择约定交货日期')
        return false
      } else if (!this.orderFrom.detailsList.length) {
        this.$message.error('请添加货品清单')
        return false
      } else if (inBidFlag) {
        this.$message.error('请填写完整货品清单内容，或删除不需要的货品')
        return false
      } else if (!this.orderFrom.approveDtoList.length) {
        this.$message.error('审核人员不能为空，请添加审核人员')
        return false
      }

      // 为审核人添加审核顺序
      this.orderFrom.approveDtoList.forEach((item, index) => {
        this.$set(item, 'approveSort', index)
      })
      let url = '/contractOrder/addContractOrder'
      if (this.orderId) {
        url = '/contractOrder/updContractOrder'
      }
      this.$https({
        method: 'post',
        url: url,
        data: this.orderFrom
      }).then(res => {
        if (res.code === 0) {
          this.$message.success(res.msg)
          this.$emit('close')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    closeBtn() {
      this.$emit('close')
    },
    // 删除表格材料
    delTableItem(index) {
      this.orderFrom.detailsList.splice(index, 1)

      this.calculatePrice()
    },
    // 计算总价
    calculatePrice() {
      let price = 0
      this.orderFrom.detailsList.forEach(item => {
        if (item.purchaseQuantity && item.unitPrice) {
          price = price + +(item.purchaseQuantity * item.unitPrice)
        }
      })
      this.orderFrom.amountPrice = price.toFixed(2)
    },
    selectFocus(e, id) {
      // 根据材料id获取规格型号
      if (e) {
        if (id) {
          this.$https({
            url: '/material/listMaterialSpecsByMaterialId/?materialId=' + +id,
            method: 'post'
          })
            .then(res => {
              if (res.code === 0) {
                this.orderFrom.detailsList.forEach(element => {
                  if (id === element.materialId) {
                    this.$set(element, 'modelSelectList', res.data)
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          this.$message.error('请选择材料名称')
        }
      }
    },
    // 规格型号改变时设置单位
    categoryChange(val) {
      this.orderFrom.detailsList.forEach(element => {
        if (val === element.model) {
          element.modelSelectList.forEach(el => {
            if (el.specsName === val) {
              this.$set(element, 'company', el.materialUnit)
            }
          })
        }
      })
    },
    // 合同外
    newMaterialClose(val) {
      if (val) {
        val.forEach(item => {
          this.orderFrom.detailsList.push({
            productTypes: 2,
            materialId: item.id,
            materialName: item.materialName,
            model: '',
            company: '',
            parameterIndex: '',
            unitPrice: 0,
            purchaseQuantity: 0,
            totalPrice: 0,
            modelSelectList: []
          })
        })
      }
      this.materialVisible = false
    },
    // 添加合同内材料弹窗关闭
    materialClose(val) {
      if (val) {
        this.orderFrom.detailsList = this.orderFrom.detailsList.concat(val)
        this.calculatePrice()
      }
      this.addMaterialVisiable = false
    },
    addMaterial(val) {
      if (val === '合同内') {
        if (this.orderFrom.contractId) {
          this.addMaterialVisiable = true
        } else {
          this.$message.error('请先选择合同编号')
        }
      } else {
        if (this.orderFrom.contractId) {
          this.materialVisible = true
        } else {
          this.$message.error('请先选择合同编号')
        }
      }
    },
    //选择人员弹窗关闭
    personClose(e) {
      if (this.personType == 'reviewer') {
        this.reviewerList[this.reviewerIndex].approverName = e.userName
        this.reviewerList[this.reviewerIndex].approverId = e.id
      }

      this.personVisible = false
    },
    //添加审核人
    addReviewer() {
      if (this.reviewerList.length < 5) {
        this.reviewerList.push({
          approverName: '',
          approverId: ''
        })
      } else {
        this.$message.error('最多添加5位审核人员')
      }
    },
    //删除审核人
    colseReviewer(index) {
      if (this.reviewerList.length > 1) {
        this.$confirm('是否删除审核人?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.reviewerList.splice(index, 1)
          })
          .catch(() => {})
      } else {
        this.$message.error('审核人不能少于一个')
      }
    },
    //选择联系人
    personnelSelect(type, index) {
      this.reviewerIndex = index
      this.personVisible = true
      this.personType = type
    },
    // 下拉合同编号
    contractChange(val) {
      this.conOptions.forEach(item => {
        if (item.id == val) {
          this.orderFrom.contractNo = item.contractNo
          this.orderFrom.proName = item.proName
          this.orderFrom.proId = item.proId
          this.orderFrom.providerName = item.providerName
          this.orderFrom.contractBuyer = item.contractBuyer
          this.orderFrom.enterpriseName = item.enterpriseName
          this.orderFrom.area = item.area
          this.orderFrom.areaId = item.areaId
          this.orderFrom.city = item.city
          this.orderFrom.providerId = item.bidCompanyId
          this.orderFrom.cityId = item.cityId
          this.orderFrom.provinceId = item.provinceId
          this.orderFrom.province = item.province
          this.orderFrom.detailAddress = item.detailAddress
          this.noAndName = item.numberAndName
          this.createTime = item.createTime

          this.provinceChange(this.orderFrom.provinceId)
          this.cityChange(this.orderFrom.cityId)
          this.getContractList()
        }
      })
    },

    //获取省份
    getSelect() {
      this.common.getAddressList('province').then(value => {
        this.provinceOptions = value
      })
    },
    //选完省后获取市
    provinceChange(e, clear) {
      if (clear) {
        this.orderFrom.city = ''
        this.orderFrom.area = ''
        this.orderFrom.cityId = ''
        this.orderFrom.areaId = ''
      }
      this.provinceOptions.forEach(item => {
        if (e == item.provinceId) {
          this.orderFrom.province = item.province
        }
      })

      this.common.getAddressList('city', e).then(value => {
        this.cityOptions = value
      })
    },
    //选完市后获取区
    cityChange(e, clear) {
      if (clear) {
        this.orderFrom.area = ''
        this.orderFrom.areaId = ''
      }
      this.cityOptions.forEach(item => {
        if (e == item.cityId) {
          // 设置区名
          this.orderFrom.city = item.city
        }
      })
      this.common.getAddressList('area', e).then(value => {
        this.areaOptions = value
      })
    },
    // 选择区时设置区名
    areaChange(e) {
      this.areaOptions.forEach(item => {
        if (e == item.areaId) {
          this.orderFrom.area = item.area
        }
      })
    },
    getOrderData() {
      this.$https({
        method: 'post',
        url: '/contractOrder/contractOrderDetails?id=' + this.orderId
      })
        .then(res => {
          if (res.code === 0) {
            this.orderFrom = res.data
            this.createTime = res.data.takeEffectDate
            this.noAndName = res.data.contractNo + '-' + res.data.proName
            this.reviewerList =
              res.data.approveDtoList && res.data.approveDtoList.length
                ? res.data.approveDtoList
                : [{ approverName: '', approverId: '' }]
            this.provinceChange(this.orderFrom.provinceId)
            this.cityChange(this.orderFrom.cityId)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getData() {
      this.$https({
        method: 'post',
        url: '/contract/getContractProNameList'
      })
        .then(res => {
          if (res.code == 0) {
            this.conOptions = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 获取当前合同内的采购订单
    getContractList() {
      this.$https({
        method: 'post',
        url: '/contract/queryContractPurchaseList',
        data: {
          id: this.orderFrom.contractId,
          productTypes: 1
        }
      })
        .then(res => {
          if (res.code === 0) {
            this.orderFrom.detailsList = res.data
            this.calculatePrice()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    tabRowClassName({ row, rowIndex }) {
      let index = rowIndex + 1
      if (index % 2 == 0) {
        return 'warning-row'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.btn_box {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
.commonFrom {
  margin-top: 7px;
  width: 88%;
  .el-form-item {
    width: 40% !important;
    margin-bottom: 7px !important;
  }
  .form-item {
    width: 100% !important;
    /deep/.el-form-item__content {
      display: flex;
    }
    .el-input {
      width: 260px;
    }
  }

  .performance_text {
    color: #999;
    font-size: 14px;
  }
  .icon-guanbianniu {
    font-size: 16px;
    cursor: pointer;
    margin-left: 10px;
  }
  .icon-guanbianniu:hover {
    color: #fa7355;
  }
}
h1 {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #fa7355;
  span {
    font-weight: normal;
    color: #999;
  }
}
.ty {
  color: #ff3d3d;
}
.footer {
  .commonBtn,
  .commonBtn1 {
    width: 130px;
  }
  text-align: center;
  margin-top: 20px;
}
.mgn {
  margin-top: 20px;
}
.auditfrom {
  margin: 16px 0 0;
  .el-form-item {
    width: 43% !important;
    margin-bottom: 16px !important;
  }
}
</style>
